package net.ankao.job.common;

import lombok.extern.slf4j.Slf4j;
import net.ankao.job.core.rpc.IAkJobClientService;
import net.ankao.job.entity.AkApplicationClient;
import org.springframework.stereotype.Component;

import java.rmi.Naming;
import java.util.HashMap;
import java.util.concurrent.*;

/**
 * @author LILU
 * @date 2024-11-28 10:14
 */
@Slf4j
@Component
public class HeartbeatNamingManager {


    private HashMap<String, IAkJobClientService> namingMap = new HashMap<>();

    public IAkJobClientService getNaming(String clientId) {
        return namingMap.get(clientId);
    }

    public IAkJobClientService delNaming(String clientId) {
        return namingMap.remove(clientId);
    }


    public void addNaming(AkApplicationClient akApplicationClient) {
        String rmiUrl = "rmi://" + akApplicationClient.getClientUrl() + ":"
                + akApplicationClient.getClientPort() + "/"
                + Constant.CLIENT_CLASS_NAME;
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<IAkJobClientService> future = executor.submit(() -> (IAkJobClientService) Naming.lookup(rmiUrl));
        try {
            // 尝试在2秒内获取结果
            IAkJobClientService jobClientService = future.get(2, TimeUnit.SECONDS);
            namingMap.put(akApplicationClient.getId(), jobClientService);
        } catch (TimeoutException e) {
        } catch (InterruptedException | ExecutionException e) {
        } finally {
            future.cancel(true);
            executor.shutdownNow();
        }

    }


}
